﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using ZHDJ.Core;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Log;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.Box;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Org;

namespace ZHDJ.WebPage
{
    public class DBPageBase : System.Web.UI.Page
    {
        #region 属性 常量
        /// <summary>
        /// 
        /// </summary>
        public MemoryCacheManager MemoryCache = new MemoryCacheManager();

        public static readonly string SK_ONLINE_UPDATE_TIME = "OnlineUpdateTime";

        /// <summary>
        /// 网站域名
        /// </summary>
        public string WebHost
        {
            get { return SystemParameterCaching.Get(SystemParameterKey.WebHost); }
        }
        #endregion

        protected void Page_Init(object sender, EventArgs e)
        {
            if (HttpContext.Current != null)

            {
                try
                {
                    if (Request.Url.ToString().ToLower().Contains("/errors/"))
                    {
                        return;
                    }
                    var id = UserLogID;
                    if (string.IsNullOrEmpty(id))
                    {
                        return;
                    }
                    
                    PartyUserLoginLog.UpdateLastOpTimeBy(UserLogID);

                }
                catch (Exception ex)
                {
                    Log4netHelper.WriteLog(ex);
                }
            }
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            try
            {
                string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }

                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.UserHostAddress;
                }
                var path = Request.Url.AbsoluteUri.ToLower().Split('/');
                var sign = "";
                for (int i = 0; i < path.Length; i++)
                {
                    if (path[i].Contains(".aspx"))
                    {
                        if (path[i - 1].Contains(".com"))
                        {
                            sign = "root_" + path[i].Split('?')[0];
                        }
                        else
                        {
                            sign = path[i - 1] + "_" + path[i].Split('?')[0];
                        }

                        break;
                    }
                }
                if (Request.Url.AbsoluteUri.ToLower().Contains("/app/"))
                {
                    sign = "app_" + sign;
                }
                var visti = new PartyTouristVisit()
                {
                    ID = StringHelper.NewID,
                    VistitTime = DateTime.Now,
                    IPAddress = ip,
                    SessionID = Session.SessionID,
                    VisitUrl = Request.Url.AbsoluteUri,
                    PageSign = sign
                };
                DB.PartyTouristVisits.Add(visti);
                DB.SaveChanges();
            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog(ex);
            }

        }

        #region 实体上下文
            /// <summary>
            /// 数据访问 
            /// </summary>
        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }

        #endregion

        #region 登陆相关

        /// <summary>
        /// 用户登陆日志ID
        /// </summary>
        public string UserLogID
        {
            get
            {
                if (Session["UserLogID"] != null)
                {
                    return Session["UserLogID"].ToString();
                }
                if (!IsLogin)
                {
                    return "";
                }
                
                else
                {
                    var temp = DB.PartyUserLoginLogs.Where(a => a.LoginID == CurrentUser.LoginID)
                        .OrderByDescending(a => a.LoginTime)
                        .FirstOrDefault();
                    if (temp != null)
                    {
                        Session["UserLogID"] = temp.ID;
                        return temp.ID;
                    }
                    else
                        return "";
                }
            }
        }

        private PartyOrgMember _CurrentUser
        {
            get
            {
                return Session["_CurrentUser_"] as PartyOrgMember;
            }
            set
            {
                Session["_CurrentUser_"] = value;
            }
        }

        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public PartyOrgMember CurrentUser
        {
            get
            {
                if (User.Identity.IsAuthenticated)
                {
                    if (_CurrentUser != null && _CurrentUser.LoginID == User.Identity.Name)
                    {
                        return _CurrentUser;
                    }
                    var temp = DB.PartyOrgMembers.Find(Convert.ToString(User.Identity.Name));
                    temp.ManageBranchIDs = new List<string>();
                    var dt = PartyOrg.GetBranchManageByLoginId(temp.LoginID);
                    foreach (DataRow dr in dt.Rows)
                    {
                        temp.ManageBranchIDs.Add(Convert.ToString(dr["BranchID"]));
                    }
                    _CurrentUser = temp;
                    return _CurrentUser;
                }
                return null;
            }
        }

        /// <summary>
        ///是否已登陆
        /// </summary>
        public bool IsLogin
        {
            get
            {
                return CurrentUser != null && !string.IsNullOrEmpty(CurrentUser.LoginID);
            }
        }

        /// <summary>
        ///登陆验证
        /// </summary>
        /// <param name="isAlertTooltip">是否需要弹出提示框</param>
        public void CheckLogin(string backUrl = "", bool isAlertTooltip = false)
        {
            var backUrlTemp = string.IsNullOrEmpty(backUrl) ? Request.Url.ToString() : backUrl;
            var dd = Server.UrlEncode(backUrlTemp);
            if (!IsLogin)
            {
                var url = "~/Login.aspx?backurl=" + Server.UrlEncode(backUrlTemp) + (isAlertTooltip == true ? "&AlertTooltip=true" : "");
                if (isAlertTooltip)
                {
                    RedirectTo("Login", url, a => { a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)); a.Add("AlertTooltip", "true"); });
                }
                else
                    RedirectTo("Login", url, a => a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)));
            }
        }

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="backUrlIsCurrentPage">返回页面是否当前页面</param>
        /// <param name="isAlertTooltip">是否需要弹出提示框</param>
        public void CheckLogin(bool backUrlIsCurrentPage, bool isAlertTooltip = false)
        {
            var backUrlTemp = backUrlIsCurrentPage ? Request.Url.PathAndQuery : "/default.aspx";
            var dd = Server.UrlEncode(backUrlTemp);
            if (!IsLogin)
            {
                var url = "~/Login.aspx?ReturnUrl=" + Server.UrlEncode(backUrlTemp) + (isAlertTooltip == true ? "&AlertTooltip=true" : "");
                if (isAlertTooltip)
                {
                    RedirectTo("Login", url, a => { a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)); a.Add("AlertTooltip", "true"); });
                }
                else
                    RedirectTo("Login", url, a => a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)));
            }
        }

        /// <summary>
        ///登录验证，单独处理带#字符的
        /// </summary>
        /// <param name="backUrlIsCurrentPage"></param>
        /// <param name="isAlertTooltip"></param>
        public void CheckLoginWithSymbol(bool backUrlIsCurrentPage, bool isAlertTooltip = false)
        {
            var backUrlTemp = (backUrlIsCurrentPage ? Request.Url.PathAndQuery : "/default.aspx").Replace("#","poundsign");
           
            var dd = Server.UrlEncode(backUrlTemp);
            if (!IsLogin)
            {
                var url = "~/Login.aspx?ReturnUrl=" + Server.UrlEncode(backUrlTemp) + (isAlertTooltip == true ? "&AlertTooltip=true" : "");
                if (isAlertTooltip)
                {
                    RedirectTo("Login", url, a => { a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)); a.Add("AlertTooltip", "true"); });
                }
                else
                    RedirectTo("Login", url, a => a.Add("ReturnUrl", Server.UrlEncode(backUrlTemp)));
            }
        }

        /// <summary>
        /// 是否为系统管理员
        /// </summary>
        public bool IsSystemAdmin
        {
            get
            {
                if (CurrentUser.LoginID == "admin")
                {
                    return true;
                }
                var roles = GetIdentityRoleIDs();
                return roles.Contains(SystemParameterCaching.Get(SystemParameterKey.SystemAdminRoleID));
            }
        }

        /// <summary>
        /// 当前登陆用户的角色列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetIdentityRoleIDs()
        {
            List<string> roleIDs = new List<string>();

            if (User.Identity.IsAuthenticated)
            {
                FormsAuthenticationTicket ticket = ((FormsIdentity)User.Identity).Ticket;
                string userData = ticket.UserData;

                foreach (string roleID in userData.Split(','))
                {
                    if (!String.IsNullOrEmpty(roleID))
                    {
                        roleIDs.Add(roleID);
                    }
                }
            }

            return roleIDs;
        }

        /// <summary>
        /// 当前登陆用户名
        /// </summary>
        /// <returns></returns>
        protected string GetIdentityName()
        {
            if (!User.Identity.IsAuthenticated) return "";
            return CurrentUser != null ? CurrentUser.UserName : "";
        }


        /// <summary>
        /// 创建表单验证的票证并存储在客户端Cookie中
        /// </summary>
        /// <param name="userName">当前登陆用户名</param>
        /// <param name="roleIDs">当前登陆用户的角色ID列表</param>
        /// <param name="isPersistent">是否跨浏览器会话保存票证</param>
        /// <param name="expiration">过期时间</param>
        protected void CreateFormsAuthenticationTicket(string userId, string roleIDs, bool isPersistent, DateTime expiration)
        {
            if (userId == "admin")
            {
                if (string.IsNullOrEmpty(roleIDs))
                    roleIDs = "admins";
                else
                    roleIDs += ",admins";
            }
            // 创建Forms身份验证票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                userId,                       // 与票证关联的用户名
                DateTime.Now,                   // 票证发出时间
                expiration,                     // 票证过期时间
                isPersistent,                   // 如果票证将存储在持久性 Cookie 中（跨浏览器会话保存），则为 true；否则为 false。
                roleIDs                         // 存储在票证中的用户特定的数据
             );

            // 对Forms身份验证票据进行加密，然后保存到客户端Cookie中
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            cookie.HttpOnly = true;
            // 1. 关闭浏览器即删除（Session Cookie）：DateTime.MinValue
            // 2. 指定时间后删除：大于 DateTime.Now 的某个值
            // 3. 删除Cookie：小于 DateTime.Now 的某个值
            if (isPersistent)
            {
                cookie.Expires = expiration;
            }
            else
            {
                cookie.Expires = DateTime.MinValue;
            }
            Response.Cookies.Add(cookie);
        }

        #endregion

        #region 在线用户相关

        protected void UpdateOnlineUser(string loginId)
        {
            //DateTime now = DateTime.Now;
            //object lastUpdateTime = Session[SK_ONLINE_UPDATE_TIME];
            //if (lastUpdateTime == null || (Convert.ToDateTime(lastUpdateTime).Subtract(now).TotalMinutes > 5))
            //{
            //    // 记录本次更新时间
            //    Session[SK_ONLINE_UPDATE_TIME] = now;

            //    Online online = DB.Onlines.Where(o => o.User.LoginID == loginId).FirstOrDefault();
            //    if (online != null)
            //    {
            //        online.UpdateTime = now;
            //        DB.SaveChanges();
            //    }
            //}
        }

        protected void RegisterOnlineUser(PartyOrgMember user)
        {
            //Online online = DB.Onlines.Where(o => o.User.LoginID == user.LoginID).FirstOrDefault();

            //// 如果不存在，就创建一条新的记录
            //if (online == null)
            //{
            //    online = new Online();
            //    online.ID = StringHelper.NewID;
            //    DB.Onlines.Add(online);
            //}
            //DateTime now = DateTime.Now;

            //online.User = user;
            //online.IPAdddress = Request.UserHostAddress;
            //online.LoginTime = now;
            //online.UpdateTime = now;

            //DB.SaveChanges();

            //// 记录本次更新时间
            //Session[SK_ONLINE_UPDATE_TIME] = now;

        }

        /// <summary>
        /// 在线人数
        /// </summary>
        /// <returns></returns>
        protected int GetOnlineCount()
        {
            return 0;
            //DateTime lastM = DateTime.Now.AddMinutes(-15);
            //return DB.Onlines.Where(o => o.UpdateTime > lastM).Count();
        }

        #endregion


        /// <summary>
        /// 页面跳转
        /// </summary>
        /// <param name="toType">跳转类型</param>
        /// <param name="url">默认地址</param>
        /// <param name="para">url参数</param>
        public void RedirectTo(string toType, string url, Action<Dictionary<string, string>> para = null)
        {
            if (SystemParameterCaching.Get(SystemParameterKey.EnableRedirectTo) != "1")
            {
                Response.Redirect(url);
            }
            else
            {
                PageUtility.RedirectTo(this, WebHost, toType, url, para);

            }
        }
        /// <summary>
        /// 跳转到首页
        /// </summary>
        public void RedirectToDefault()
        {
            RedirectTo("default", "~/default.aspx");
        }

    }
}
